package com.shwread.android.qysw.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000209.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;
import com.squareup.picasso.Picasso;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import logic.bean.QrCodeInfo;


/**
 * Created by x_luthy on 2016/5/29.
 */
public class QrCodeActivity
        extends
		BaseBusinessActivity
{

	private MyListView lvQrCode;
	private TextView	 tvTitle;
	private Button		 butBack;
	private List<QrCodeInfo.QrCodeListBean> list;
    private int orderId;
	private int sta = -1;


	private ImageView ivTicketQrCodePic;
	private TextView tvTicketQrCodeName,tvTicketQrCodeProperty,tvTicketQrCodeOriginalPrice,
			tvTicketQrCodeOriginalCount;
	//验证码没生成之前显示
	private  TextView tVEmptyView;
//	private MyReceiver receiver=null;
	private QrCodeAdapter qrCodeAdapter;
	private Intent intentService = null;
	private LoadingView loadingView;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.arg1==0){
				NewActionHelp.qryTicketOrderBarcode(QrCodeActivity.this, orderId, new GetDataReq());
			}
		}
	};

	@Override
	public Handler getUIHandler() {
		return null;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qrcode);

		lvQrCode = (MyListView) findViewById(R.id.lvQrCode);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		butBack = (Button) findViewById(R.id.common_header_back);
		ivTicketQrCodePic = (ImageView) findViewById(R.id.ivTicketQrCodePic);
		tvTicketQrCodeName = (TextView) findViewById(R.id.tvTicketQrCodeName);
		tvTicketQrCodeProperty = (TextView) findViewById(R.id.tvTicketQrCodeProperty);
		tvTicketQrCodeOriginalPrice = (TextView) findViewById(R.id.tvTicketQrCodeOriginalPrice);
		tvTicketQrCodeOriginalCount = (TextView) findViewById(R.id.tvTicketQrCodeOriginalCount);
		tVEmptyView = (TextView) findViewById(R.id.tVEmptyView);

		loadingView = (LoadingView)findViewById(R.id.my_goods_loading_view);
		loadingView.setLoadingAnim(R.drawable.home_progress);
		loadingView.setVisibility(View.VISIBLE);
		loadingView.changeLoadingStatus(0);

		tvTitle.setText("验证码");
		butBack.setVisibility(View.VISIBLE);
		butBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (sta!=-1) {
					Intent intent = new Intent();
					intent.putExtra("status", sta);
					setResult(1000, intent);
				}
				QrCodeActivity.this.finish();
			}
		});
		list = new ArrayList<>();
        orderId = getIntent().getIntExtra("orderId",-1);
		qrCodeAdapter = new QrCodeAdapter();
		lvQrCode.setAdapter(qrCodeAdapter);
        NewActionHelp.qryTicketOrderBarcode(QrCodeActivity.this, orderId, new GetDataReq());
		new MyThread().start();
	}
	private class MyThread extends Thread {
		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(2000);
					Message msg = handler.obtainMessage();
					msg.arg1 = 0;
					handler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void onBackPressed() {
		if (sta!=-1) {
			Intent intent = new Intent();
			intent.putExtra("status", sta);
			setResult(1000, intent);
		}
		QrCodeActivity.this.finish();
		super.onBackPressed();
	}

	class QrCodeAdapter
	        extends
	        BaseAdapter
	{

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder mHolder = null;
			if (convertView == null)
			{
				mHolder = new ViewHolder();
				convertView = LayoutInflater.from(QrCodeActivity.this).inflate(R.layout.item_lv_qrcode, null);
				mHolder.tvQrCodeTitle = (TextView) convertView.findViewById(R.id.tvQrCodeTitle);
				mHolder.ivQrCodePic = (ImageView) convertView.findViewById(R.id.ivQrCodePic);
				mHolder.ivQrCodeIsChecked = (ImageView) convertView.findViewById(R.id.ivQrCodeIsChecked);
				convertView.setTag(mHolder);
			}
			else
			{
				mHolder = (ViewHolder) convertView.getTag();
			}
//			"status":0,"status":0 //int 状态 0=未使用 1=已过期 2=已使用
			mHolder.tvQrCodeTitle.setText("验证码"+(position+1)+"：");
			int status = list.get(position).getStatus();
			if (status==0){
				mHolder.ivQrCodeIsChecked.setVisibility(View.GONE);
				mHolder.tvQrCodeTitle.setTextColor(Color.parseColor("#ff8000"));
			}else if(status==1){
				mHolder.ivQrCodeIsChecked.setVisibility(View.GONE);
				mHolder.tvQrCodeTitle.setTextColor(Color.parseColor("#b7b7b7"));
			}else if(status==2){
				mHolder.ivQrCodeIsChecked.setVisibility(View.VISIBLE);
				mHolder.tvQrCodeTitle.setTextColor(Color.parseColor("#ff8000"));
			}
			Picasso.with(QrCodeActivity.this).load(list.get(position).getBarcodeImg()).into(mHolder.ivQrCodePic);
			return convertView;
		}

		class ViewHolder
		{
			private TextView  tvQrCodeTitle;
			private ImageView ivQrCodePic,ivQrCodeIsChecked;
		}
	}

	private class GetDataReq
	        extends
			ObjectHttpResponseHandler<QrCodeInfo>
	{

		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			Logger.e("错误状态码--------" + Integer.toString(statusCode));
			loadingView.setVisibility(View.GONE);
			loadingView.changeLoadingStatus(2);
		}

        @Override
        public Type getType() {
            return new TypeToken<QrCodeInfo>(){}.getType();
        }

        @Override
		public void onSuccess(int statusCode, Header[] headers, QrCodeInfo object, String responseString) {
			loadingView.setVisibility(View.GONE);
			loadingView.changeLoadingStatus(2);
			list = object.getUserTicketDtoList();
			sta = Integer.parseInt(object.getOrderInfo().getStatus());
			Log.e("验证码shuju",object.toString());
			Picasso.with(QrCodeActivity.this)
					.load(object.getOrderInfo().getTicketImg())
					.error(R.drawable.atlas_default_img)
					.placeholder(R.drawable.atlas_default_img)
					.into(ivTicketQrCodePic);
			tvTicketQrCodeName.setText(object.getOrderInfo().getSpotName());
			tvTicketQrCodeProperty.setText(object.getOrderInfo().getPropertyName());
			DecimalFormat df = new DecimalFormat("0.0");
			tvTicketQrCodeOriginalPrice.setText("总价：￥"+df.format(object.getOrderInfo().getTotalMoney()/100));
			tvTicketQrCodeOriginalCount.setText("数量："+object.getOrderInfo().getAmount());
			if (null==list||list.size()==0){
				tVEmptyView.setVisibility(View.VISIBLE);
			}
			qrCodeAdapter.notifyDataSetChanged();
//			qrCodeAdapter = new QrCodeAdapter();
//			lvQrCode.setAdapter(qrCodeAdapter);

			//服务开启，注册广播
//			intentService = new Intent(QrCodeActivity.this, QrCodeStatuService.class);
//			intentService.putExtra("orderId",orderId);
//			intentService.putExtra("data", (Serializable) list);
//			startService(intentService);
//			receiver=new MyReceiver();
//			IntentFilter filter=new IntentFilter();
//			filter.addAction("com.shwread.android.qysw.QrCodeStatuService");
//			QrCodeActivity.this.registerReceiver(receiver,filter);
		}
	}

	//接受广播，判断门票状态是不是改变
//	public class MyReceiver extends BroadcastReceiver {
//		@Override
//		public void onReceive(Context context, Intent intent) {
//			Bundle bundle=intent.getExtras();
//			list = (List<QrCodeInfo.QrCodeListBean>) bundle.getSerializable("data");
////			int st = bundle.getInt("status");
//
//			qrCodeAdapter.notifyDataSetChanged();
//		}
//	}

//	@Override
//	protected void onDestroy() {
//		stopService(intentService);
//		super.onDestroy();
//	}
}
